package com.example.security.demo.config;

import com.example.security.demo.filter.TokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author zhanpengguo
 * @date 2019-10-08 14:34
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)/*开启权限注解*/
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    SecurityHandler securityHandler;
    @Autowired
    TokenFilter tokenFilter;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //不使用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.formLogin()
                .loginPage("/")
                /*登录成功处理器和登录失败处理器*/
                .loginProcessingUrl("/login").successHandler(securityHandler).failureHandler(securityHandler)
                .permitAll()
                .and()
                /*未登录处理器和无权限处理器*/
                .exceptionHandling().authenticationEntryPoint(securityHandler).accessDeniedHandler(securityHandler)
                .and()
                .authorizeRequests()
                .antMatchers("/","/user/*","/hello","/gen/*","/*.html").permitAll()
                .anyRequest().authenticated()
                .and()
                .logout().logoutUrl("/logout").logoutSuccessHandler(securityHandler)
                .and()
                .csrf()
                .disable();
        //添加自定义拦截器
        http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
